import cv2
import os
import shutil
from tqdm import tqdm
import file.file as file
import logging


def splitVedio2Image(vedioPath, imageDir, timeF):
    """
    将视频切割为图片
    :param vedioPath: 视频路径
    :param imageDir: 图片保存路径
    :param timeF:视频帧计数间隔频率
    :return:
    """
    # 使用opencv按一定时间间隔截取视频帧，并保存图片
    vc = cv2.VideoCapture(vedioPath)
    c = 1

    if vc.isOpened():  # 判断是否正常打开
        rval, frame = vc.read()
    else:
        rval = False
    # 循环读取桢
    while rval:
        rval, frame = vc.read()
        if c % timeF == 0:
            imageName = str(c) + '.jpg'
            try:
                # 存储图片
                cv2.imwrite(os.path.join(imageDir, imageName), frame)
            except:
                continue
        c = c + 1
        cv2.waitKey(1)
    vc.release()

if __name__ == '__main__':
    vedioDir = 'G:\\experimentCode\\python-tools\\video\\video'
    surfix = '.avi'
    vedioList = file.GetAllFileNameBySurfix(vedioDir, surfix)
    print(vedioList)

    imageDir = 'G:\\experimentCode\\python-tools\\video\\image\\split_vedio_to_image'
    timeF = 25

    for vedioName in tqdm(vedioList):
        vedioPath = os.path.join(vedioDir, vedioName)
        subImageDir = os.path.join(imageDir, os.path.splitext(vedioName)[0])
        if not os.path.exists(subImageDir):
            os.mkdir(subImageDir)
        else:
            shutil.rmtree(subImageDir)
            os.mkdir(subImageDir)
        splitVedio2Image(vedioPath, subImageDir, timeF)
